package com.anxinr.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anxinr.pojo.dto.QueryBodyDTO;
import com.anxinr.pojo.dto.RequestBodyInfoDTO;
import com.anxinr.pojo.entity.Project;
import com.anxinr.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author anxinr
 */
@Slf4j
@RestController
@RequestMapping("/interface")
public class InterfaceTestController {

    @Autowired
    private RestTemplate template ;

    @PostMapping("/test")
    public Result<RequestBodyInfoDTO> interfaceTest(@RequestBody RequestBodyInfoDTO info) throws Exception {
        try {
            if (Objects.isNull(info)) {
                throw new Exception("请求信息不能为空!");
            }
            if (Objects.isNull(info.getRequestType())){
                throw new Exception("请求方式不能为空!");
            }
            if (Objects.isNull(info.getRequestBodyType())){
                throw new Exception("请求体类型不能为空!");
            }
            /**处理请求*/
            handleRequestInfo(info);
            return new Result(info);
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
    }

    private void handleRequestInfo(RequestBodyInfoDTO info) {
        /**获取请求信息*/
        String url = info.getUrl();
        String requestBodyType = "";
        String requestMethod = "";
        /**请求类型*/
        Integer requestType = info.getRequestType();
        if (Integer.valueOf("1").equals(requestType)){
            requestMethod = "POST" ;
        }else {
            requestMethod = "GET" ;
        }
        /**请求体类型*/
        Integer bodyType = info.getRequestBodyType();

        /**处理请求*/
        handleRequest(url,requestMethod,requestBodyType,info) ;
    }

    private void handleRequest(String url, String requestMethod, String requestBodyType, RequestBodyInfoDTO info) {
        ResponseEntity<HashMap> responseEntity = null;
        StringBuilder sb = new StringBuilder();
        List<QueryBodyDTO> list = info.getList();
        sb.append(url) ;
        /**区分POST与GET方式*/
        if ("POST".equals(requestMethod)){
            //1、构建body参数
            JSONObject jsonObject = new JSONObject();
            if (CollectionUtil.isNotEmpty(list)){
                for (QueryBodyDTO dto : list) {
                    jsonObject.put(dto.getKey(),dto.getValue()) ;
                }
            }
            if (!Objects.isNull(info.getBody())){
                jsonObject = JSON.parseObject(JSON.toJSONString(info.getBody()));
            }
            //2、添加请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type","application/json");

            //3、组装请求头和参数
            HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(jsonObject), headers);

            //4、发起post请求
            /**请求接口*/
            try {
                responseEntity = template.postForEntity(sb.toString(), formEntity, HashMap.class);
                log.info("ResponseEntity -> {}",responseEntity);
            } catch (RestClientException e) {
                e.printStackTrace();
                throw e ;
            }
        }else {
            if (CollectionUtil.isNotEmpty(list)){
                if (url.contains("?")){
                    for (QueryBodyDTO queryBodyDTO : list) {
                        sb.append("&").append(queryBodyDTO.getKey()).append("=").append(queryBodyDTO.getValue());
                    }
                }else {
                    sb.append("?") ;
                    for (int i = 0; i < list.size(); i++) {
                        if (i == list.size() -1){
                            sb.append(list.get(i).getKey()).append("=").append(list.get(i).getValue());
                        }else {
                            sb.append(list.get(i).getKey()).append("=").append(list.get(i).getValue()).append("&");
                        }
                    }
                }
            }
            /**请求接口*/
            try {
                responseEntity = template.getForEntity(sb.toString(), HashMap.class);
            }catch (Exception e){
                e.printStackTrace();
                throw e ;
            }
        }
        /**处理返回信息*/
        String responseData = JSON.toJSONString(responseEntity.getBody());
        info.setResponseBody(responseData);
    }


}
